package org.duang.kit;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

import org.duang.db.sql.SqlBaseDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ThreadPoolKit {
	
	private final static Logger logger = LoggerFactory.getLogger(ThreadPoolKit.class);

	private static int MAX_POOL_NUMBER = 20;

	// 创建线程池
	private static ExecutorService es = Executors.newFixedThreadPool(MAX_POOL_NUMBER, new NamedThreadFactory());

	// 执行线程
	public static void execute(Thread thread){
		try{
			es.execute(thread);
		} catch( Exception e ) {
			logger.warn("ThreadPoolKit execute is error: "+ e.getMessage(), e);
		}
	}

	static class NamedThreadFactory implements ThreadFactory {
		private static final AtomicInteger pool_seq = new AtomicInteger(1);
		private final AtomicInteger mThreadNum = new AtomicInteger(1);
		private final String mPrefix;
		private final ThreadGroup mGroup;

		public NamedThreadFactory() {
			mPrefix = "duang-" + pool_seq.getAndIncrement() + "-thread-";
			SecurityManager s = System.getSecurityManager();
			mGroup = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup();
		}

		public Thread newThread(Runnable runnable) {
			String name = mPrefix + mThreadNum.getAndIncrement();
			Thread ret = new Thread(mGroup, runnable, name, 0);
			ret.setDaemon(false);
			return ret;
		}

		public ThreadGroup getThreadGroup() {
			return mGroup;
		}
	}
}
